export default defineNuxtPlugin(() => {
  const user = useState('user', () => null)
  const isLoggedIn = useState('isLoggedIn', () => false)

  // 检查本地存储中的用户信息
  const checkAuth = () => {
    if (process.client) {
      const storedUser = localStorage.getItem('user')
      const token = localStorage.getItem('token')
      
      if (storedUser && token) {
        try {
          const userData = JSON.parse(storedUser)
          user.value = userData
          isLoggedIn.value = true
        } catch (error) {
          console.error('Error parsing user data:', error)
          localStorage.removeItem('user')
          localStorage.removeItem('token')
        }
      }
    }
  }

  // 登录
  const login = (userData, token) => {
    user.value = userData
    isLoggedIn.value = true
    localStorage.setItem('user', JSON.stringify(userData))
    localStorage.setItem('token', token)
  }

  // 登出
  const logout = () => {
    user.value = null
    isLoggedIn.value = false
    localStorage.removeItem('user')
    localStorage.removeItem('token')
  }

  // 更新用户信息
  const updateUser = (userData) => {
    if (user.value) {
      user.value = { ...user.value, ...userData }
      localStorage.setItem('user', JSON.stringify(user.value))
    }
  }

  // 刷新用户信息
  const refreshUserInfo = async () => {
    if (isLoggedIn.value && process.client) {
      try {
        const { userApi } = await import('~/public/utils/api')
        const result = await userApi.getUserInfo()
        if (result.data) {
          updateUser(result.data)
        }
      } catch (error) {
        console.error('Failed to refresh user info:', error)
      }
    }
  }

  // 初始化时检查认证状态
  if (process.client) {
    checkAuth()
  }

  return {
    provide: {
      auth: {
        user: readonly(user),
        isLoggedIn: readonly(isLoggedIn),
        login,
        logout,
        checkAuth,
        updateUser,
        refreshUserInfo
      }
    }
  }
}) 